from __future__ import absolute_import

from json import dumps, loads


class JSONable(object):
    def to_jsonable(self, **kwargs):
        '''return a dict that can be send to the JSON-Server,
           where it will be JSONified'''
        re = {}  # '_type': self._descriptor.tablename}
        for attr in self._json_attrs:
            data = getattr(self, attr)
            re[attr] = to_jsonable(data)
        return re


def to_jsonable(value):
    if hasattr(value, 'to_jsonable'):
        return value.to_jsonable()
    elif isinstance(value, (list, tuple, set)):
        return [to_jsonable(i) for i in value]
    elif isinstance(value, dict):
        return {unicode(key): to_jsonable(value) for key, value in value.items()}
    else:
        return value